#include <eventpp/eventpp.h>
using namespace eventpp;

#include <string.h>

#include <iostream>
using namespace std;

struct echo_handler : public tcp_handler {
	virtual void on_connected( tcp_connection * conn) 
	{
		cout << "--echo client connected to server." << endl;
        say(conn);
	}

	virtual void on_read(tcp_connection * conn)
	{
		cout << "--echo client read from server." << endl;
        char buffer[1024] = {0};
        size_t read = conn->read(buffer, sizeof(buffer));

//		evbuffer *in = conn->get_input();
//		printf("Received %zu bytes\n", evbuffer_get_length(in));
		printf("----- data ----\n");
		printf("%.*s\n", read, buffer);
        static size_t times = 0;
        if (times < 2) {
            say(conn);
            ++times;
        }
	}

	virtual void on_write(tcp_connection * conn )
	{
		cout << "--echo client write to server." << endl;
		evbuffer *out = conn->get_output();
		printf("output buffer %zu bytes\n", evbuffer_get_length(out));
	}

  virtual void on_closed( tcp_connection * conn )
  {
    printf( "--echo client disconnected to server.\n" );
    conn->close();
  }
private:
    void say(tcp_connection * conn) {
        const char * m = "hello";
        conn->write( m, strlen(m) );
        cout << "-- saying: " << m << endl;
    }
};

int main(int argc, char **argv)
{
    net_base base;

    struct sockaddr_in sin;
    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
    sin.sin_port = htons(9000); /* Port 8080 */


	echo_handler h;
	tcp_connection conn(base, &h );
	conn.connect( (sockaddr *)&sin, sizeof(sin) );

  base.run();

	return 0;
}
